<template>
  <el-dialog
    width="500px"
    class="file-import-dialog"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
    :title="dialogTitle"
    :visible="dialogVisible"
    :before-close="beforeClose"
    @close="close"
  >
    <el-upload
      v-if="dialogVisible"
      ref="upload"
      drag
      class="upload-demo"
      :headers="headers"
      :action="uploadAction"
      :accept="accept"
      :file-list.sync="fileList"
      :limit="limit"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :auto-upload="false"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip fbc">
        <span>{{ uploadRemarks }}</span>
      </div>
    </el-upload>

    <span slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitData">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import util from "@/libs/util";
import { DictKeys } from "api/sys/dict";
import { getPublicConfig } from "libs/getPublicConfig";

export default {
  mixins: [dialogMixin],
  props: {
    // 弹窗标题
    dialogTitle: {
      type: String,
      default: "",
    },
    // 文件上传接口
    action: {
      type: String,
      default: "",
    },
    // 导入模板类型（参考数据字典import_template）
    importTemplateType: {
      type: String,
      default: "",
    },
    // 允许上传的文件格式
    accept: {
      type: String,
      default: ".xls,.xlsx",
    },
    // 上传要求
    uploadRemarks: {
      type: String,
      default: '仅允许导入"xls"或"xlsx"格式文件',
    },
    // 文件上传个数限制
    limit: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      // 文件上传列表
      fileList: [],
      // 文件导入模板列表配置文件
      importTemplateOptions: [],
    };
  },
  computed: {
    /**
     * 上传接口拼接
     */
    uploadAction() {
      const api = getPublicConfig({ key: "api" });
      return api + this.action;
    },
    headers() {
      return {
        Authorization: util.cookies.get("token"),
        affiliationApp: getPublicConfig({
          key: "affiliationApp",
        }),
        affiliationAppType: getPublicConfig({
          key: "affiliationAppType",
        }),
      };
    },
    /**
     * 下载链接
     */
    downloadUrl() {
      let tempObj = this.importTemplateOptions[this.importTemplateType];
      return tempObj ? tempObj.fa : "";
    },
  },
  methods: {
    /**
     * 初始化
     */
    initForm() {
      this._DictKeys();
    },
    /**
     * 弹窗关闭前的验证
     */
    beforeClose(done) {
      this.$refs.upload.abort();
      done();
    },

    /**
     * 获取导入模板
     */
    async _DictKeys() {
      try {
        const data = await DictKeys("import_template");
        if (data) {
          const { import_template: importTemplateOptions } = data;
          this.importTemplateOptions = importTemplateOptions;
        }
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 上传成功
     */
    handleSuccess(response) {
      const { code, msg } = response;
      if (code === 200) {
        this.$message.success("文件上传成功");
        this.$emit("success");
        this.close();
      } else {
        this.handleRemove();
        this.$message.error(`${msg},请重新上传`);
      }
      this.btnLoading = false;
    },
    /**
     * 上传失败(现在并没有执行这个方法)
     */
    handleError() {
      this.handleRemove();
    },
    /**
     * 删除、取消上传
     */
    handleRemove() {
      this.$refs.upload.abort();
      this.$refs.upload.clearFiles();
      this.btnLoading = false;
    },
    /**
     * 下载模板
     */
    doDownload() {
      const api = getPublicConfig({ key: "api" });
      const arr = api.split("/");
      arr.splice(arr.length - 2, 1);

      location.href = arr.join("/") + "fileUpload" + this.downloadUrl;
    },
    /**
     *  上传文件到服务器
     */
    submitData() {
      const fileArr = this.$refs.upload.uploadFiles;
      if (!fileArr.length) {
        return this.$message.error("请先选择要上传的文件");
      }
      this.btnLoading = true;
      this.$refs.upload.submit();
    },
    /**
     * 文件上传超出个数限制
     */
    handleExceed() {
      this.$message.error(`一次只能上传${this.limit}个文件`);
    },
  },
};
</script>

<style lang="scss">
.file-import-dialog {
  .el-upload-dragger {
    width: 460px !important;
  }
  .el-upload-list__item-name {
    font-size: 12px !important;
  }
}
</style>
